package com.reason.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reason.common.exception.HWException;
import com.reason.user.config.TokenDecode;
import com.reason.user.dao.*;
import com.reason.user.dto.CustomerDTO;
import com.reason.user.pojo.*;
import com.reason.user.service.CustomerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author yulongjun
 * @date 2020/6/29 10:42 下午
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ConditionMapper conditionMapper;
    @Autowired
    private EconomicsMapper economicsMapper;
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private MarriageMapper marriageMapper;
    @Autowired
    private LifeStyleMapper lifeStyleMapper;
    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public Customer findCustomer(String username) {
        if (username == null) {
            throw new RuntimeException("用户名为空");

        }
        //构造查询条件
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("name", username);

        //通过用户名查找对应的用户
        Customer customer = customerMapper.selectOne(wrapper);

        return customer;
    }

    @Override
//    @PreAuthorize("hasAnyAuthority('Vip')")//vip的客户才能查询全部
    public List<Customer> findBrandList() {
        return customerMapper.selectList(null);
    }

    @Override
    public Customer findByID(Long id) {
        return customerMapper.selectById(id);
    }

    @Override
    public int updateMember(String userId, String membership_level) {
        Customer customer = new Customer();
        customer.setId(Long.parseLong(userId));
        customer.setMember(Integer.parseInt(membership_level));
        return customerMapper.updateById(customer);
    }


    /**
     * 根据电话号吗查询对应的用户
     *
     * @param telephone
     * @return
     */
    @Override
    public Customer findByTelephone(Long telephone) {

        //设置条件
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", telephone);

        //通过电话号码查找customer用户
        Customer customer = customerMapper.selectOne(wrapper);


        return customer;
    }

    /**
     * 注册用户成为一级用户（意思就是只是手机号登陆，其他信息都没有的状态）
     *
     * @param customer
     */
    @Override
    public void register(Customer customer) {
        //如果注册信息不为空
        if (customer != null) {
            customer.setPassword(new BCryptPasswordEncoder().encode(customer.getPassword()));
            int insert = customerMapper.insert(customer);
            if (insert > 0) {
                System.out.println("注册一级会员成功!!");

            }
        }

    }


    /**
     * 注册成为二级会员(意思就是添加必须要填的资料)
     *
     * @param customer
     */
    @Override
    public boolean registerSeniorMember(Customer customer) {
        //首先用户不能为空
        if (customer != null) {
            Long id = customer.getId();
            Customer originCustomer = customerMapper.selectById(id);
            if (id == null) {
                return false;
            }
            //用户昵称
            String nick = customer.getNick();
            originCustomer.setNick(nick);
            //用户的年龄
            Integer age = customer.getAge();
            originCustomer.setAge(age);
            //用户的性别
            String sex = customer.getSex();
            originCustomer.setSex(sex);
            //用户的住址
            String address = customer.getAddress();
            originCustomer.setAddress(address);
            //用户的婚姻状态
            String maritalStatus = customer.getMaritalStatus();
            originCustomer.setMaritalStatus(maritalStatus);
            //用户的身高
            Integer height = customer.getHeight();
            originCustomer.setHeight(height);
            //用户的学历
            String education = customer.getEducation();
            originCustomer.setEducation(education);
            //用户的月薪
            String salary = customer.getSalary();
            originCustomer.setSalary(salary);
            //用户是否有子女
            String children = customer.getChildren();
            originCustomer.setChildren(children);
            //用户的民族
            String nation = customer.getNation();
            originCustomer.setNation(nation);
            //用户的体重
            Integer weight = customer.getWeight();
            originCustomer.setWeight(weight);
            //用户的自我介绍
            String suggest = customer.getSuggest();
            originCustomer.setSuggest(suggest);
            //用户的喜好
            String favorite = customer.getFavorite();
            originCustomer.setFavorite(favorite);

            if (nick != null) {
                //判断基本信息是否完整,完整就标记该用户的等级为"1"
                int i = customerMapper.deleteById(id);
                if (i > 0) {
                    System.out.println("用户新增之前删除成功!!");
                }
                //删除之后整体添加,用户等级该为"1"
                originCustomer.setMember(1);
                int insert = customerMapper.insert(originCustomer);
                if (insert > 0) {
                    System.out.println("用户新增成功!!");
                }
                //返回成功的成为1级别用户
                return true;
            }

            //如果基础条件没有添加完成，会员的状态为"0"
            //说明操作成功
            System.out.println("用户新增成功！但由于资料不完全，所有是0级用户");
            //返回还是0级用户，信息不全,还需继续添加
            return false;
        }

        //返回还是0级用户，信息不全,还需继续添加
        return false;
    }


    /**
     *
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public Map<String, Object> queryForCondition(Map<String, String> searchMap) {

        String nick = searchMap.get("nick");
        String sex = searchMap.get("sex");
        String age = searchMap.get("age");
        String address = searchMap.get("address");
        String education = searchMap.get("education");
        String height = searchMap.get("height");
        String marital_status = searchMap.get("marital_status");
        String salary = searchMap.get("salary");
        String car = searchMap.get("car");
        String house = searchMap.get("house");
        String children = searchMap.get("children");
        int pageNum = 1;
        int pageSize = 30;
        String pageNum1 = searchMap.get("pageNum");
        String pageSize1 = searchMap.get("pageSize");
        QueryWrapper<Customer> queryWrapper=new QueryWrapper<Customer>();


       if(StringUtils.isNotBlank(nick)){
           queryWrapper.like("nick",nick);
        }
        if (StringUtils.isNotBlank(sex)){
            queryWrapper.eq("sex",sex);
        }
        if(StringUtils.isNotBlank(age)){
            String[] split = age.split("-");
            queryWrapper.gt("age",split[0]);
            if(split.length==2){
                queryWrapper.lt("age",split[1]);
            }
        }
        if(StringUtils.isNotBlank(address)){
            queryWrapper.like("address",address);
        }
        if (StringUtils.isNotBlank(education)){
            queryWrapper.eq("education",education);
        }
        if(StringUtils.isNotBlank(height)){
            String[] split = height.split("-");
            queryWrapper.gt("height",split[0]);
            if (split.length==2){
                queryWrapper.lt("height",split[1]);
            }
        }
        if (StringUtils.isNotBlank(marital_status)){
            queryWrapper.eq("maritalStatus",marital_status);
        }
        if(StringUtils.isNotBlank(salary)){
            String[] split = salary.split("-");
            queryWrapper.gt("salary",split[0]);
            if (split.length==2){
                queryWrapper.lt("salary",split[1]);
            }
        }
        if (StringUtils.isNotBlank(car)){
            queryWrapper.eq("car",car);
        }
        if (StringUtils.isNotBlank(house)){
            queryWrapper.eq("house",house);
        }
        if (StringUtils.isNotBlank(children)){
            queryWrapper.eq("children",children);
        }
        if (StringUtils.isNotBlank(pageSize1)){
           pageSize= Integer.parseInt(pageSize1);
        }
        if (StringUtils.isNotBlank(pageNum1)){
            pageNum= Integer.parseInt(pageNum1);
        }

        Page<Customer> page = new Page<>(pageNum, pageSize);

        IPage<Customer> iPage = customerMapper.selectPage(page, queryWrapper);
        List<Customer> records = iPage.getRecords();
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("list",records);
        resultMap.put("total",iPage.getTotal());
        resultMap.put("totalPages",iPage.getPages());

        return resultMap;
    }

    /**
     * 查询个人信息
     * @param cusid
     * @return
     */
    @Override
    public Map<String, Object> queryForById(Long cusid) {
        Customer customer = customerMapper.selectById(cusid);
        Long condition_id = customer.getConditionId();
        Long economics_id = customer.getEconomicsId();
        Long job_id = customer.getJobId();
        Long marriage_id = customer.getMarriageId();
        Long lifeStyle_id = customer.getLifestyleId();


        Condition condition = conditionMapper.selectById(condition_id);
        Economics economics = economicsMapper.selectById(economics_id);
        Job job = jobMapper.selectById(job_id);
        Marriage marriage = marriageMapper.selectById(marriage_id);
        LifeStyle lifeStyle = lifeStyleMapper.selectById(lifeStyle_id);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("customer", customer);
        data.put("condition", condition);
        data.put("lifeStyle", lifeStyle);
        data.put("job", job);
        data.put("marriage", marriage);
        return data;
    }

    @Override
    @Transactional
    public boolean updateDetail(CustomerDTO customerDTO) {
        int i = customerMapper.updateById(customerDTO.getCustomer());
//        if (i != 1) {
//            throw new HWException("修改信息失败");
//        }
//        int i1 = conditionMapper.updateById(customerDTO.getCondition());
//        if (i1 != 1) {
//            throw new HWException("修改信息失败");
//        }
//        int i2 = jobMapper.updateById(customerDTO.getJob());
//        if (i2 != 1) {
//            throw new HWException("修改信息失败");
//        }
//        int i3 = lifeStyleMapper.updateById(customerDTO.getLifeStyle());
//        if (i3 != 1) {
//            throw new HWException("修改信息失败");
//        }
//        int i4 = marriageMapper.updateById(customerDTO.getMarriage());
//        if (i4 != 1) {
//            throw new HWException("修改信息失败");
//        }
        return true;
    }

    /**
     * 查询年龄相仿、住址相近的用户信息
     * @return 用户信息集合
     */
    @Override
    public List<Customer> findSimilarList(Long id){
//        Map<String, String> userInfo = tokenDecode.getUserInfo();
//        String username = userInfo.get("username");
//        Customer customer = findByTelephone(Long.parseLong(username));
        Customer customer = customerMapper.selectById(id);
        Integer age = customer.getAge();
        String address = customer.getAddress();
        QueryWrapper<Customer> queryWrapper=new QueryWrapper<Customer>();
        if (age != null) {
            queryWrapper.gt("age",age - 5);
            queryWrapper.lt("age",age + 5);
        }
        if (StringUtils.isNotBlank(address)) {
            queryWrapper.like("address", address);
        }
        Page<Customer> page = new Page<>(1, 8);
        IPage<Customer> iPage = customerMapper.selectPage(page, queryWrapper);
        if (iPage == null) {
            return Collections.EMPTY_LIST;
        }
        return iPage.getRecords();
    }

}